#include "chatclient.h"
#include <QDebug>

ChatClient::ChatClient(QObject *parent)
    : QObject(parent), m_socket(nullptr), m_usernameSent(false)
{
    m_socket = new QLocalSocket(this);
    
    connect(m_socket, &QLocalSocket::connected, this, &ChatClient::onConnected);
    connect(m_socket, &QLocalSocket::disconnected, this, &ChatClient::onDisconnected);
    connect(m_socket, &QLocalSocket::readyRead, this, &ChatClient::onReadyRead);
    connect(m_socket, QOverload<QLocalSocket::LocalSocketError>::of(&QLocalSocket::error),
            this, &ChatClient::onError);
}

ChatClient::~ChatClient()
{
    disconnectFromServer();
}

void ChatClient::connectToServer(const QString &serverName)
{
    if (m_socket->state() == QLocalSocket::ConnectedState) {
        return;
    }
    
    m_usernameSent = false;
    m_socket->connectToServer(serverName);
}

void ChatClient::disconnectFromServer()
{
    if (m_socket->state() == QLocalSocket::ConnectedState) {
        m_socket->disconnectFromServer();
    }
}

void ChatClient::sendMessage(const QString &content)
{
    if (m_socket->state() == QLocalSocket::ConnectedState && !m_username.isEmpty()) {
        m_socket->write((content + "\n").toUtf8());
    }
}

void ChatClient::setUsername(const QString &username)
{
    m_username = username;
}

bool ChatClient::isConnected() const
{
    return m_socket && m_socket->state() == QLocalSocket::ConnectedState;
}

QString ChatClient::username() const
{
    return m_username;
}

void ChatClient::onConnected()
{
    qDebug() << "连接到本地聊天服务器";
    emit connected();
    
    // 连接成功后发送用户名
    if (!m_username.isEmpty() && !m_usernameSent) {
        m_socket->write((m_username + "\n").toUtf8());
        m_usernameSent = true;
    }
}

void ChatClient::onDisconnected()
{
    qDebug() << "与本地聊天服务器断开连接";
    m_usernameSent = false;
    emit disconnected();
}

void ChatClient::onReadyRead()
{
    while (m_socket->canReadLine()) {
        QString data = m_socket->readLine().trimmed();
        Message msg = Message::fromString(data);
        emit messageReceived(msg);
    }
}

void ChatClient::onError(QLocalSocket::LocalSocketError error)
{
    Q_UNUSED(error);
    QString errorString = m_socket->errorString();
    qDebug() << "客户端错误:" << errorString;
    emit errorOccurred(errorString);
}